package com.sk.waste.app.views;

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.WindowManager
import android.widget.Button
import android.widget.LinearLayout.LayoutParams
import android.widget.PopupWindow
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lc.smc.lib.interfaces.LCInterface
import com.lc.smc.lib.utils.LCBaseUtil
import com.lc.smc.lib.utils.LCLogger
import com.lc.smc.lib.utils.LCSPUtil
import com.sk.waste.app.R
import com.sk.waste.app.adapters.DistrictAdapter
import com.sk.waste.app.adapters.TypeAdapter
import com.sk.waste.app.config.AppConfig
import com.sk.waste.app.config.NetWorkConfig
import com.sk.waste.app.models.MaterialModel
import com.sk.waste.app.models.SubMaterialModel
import com.sk.waste.app.models.TypeModel
import com.sk.waste.app.utils.OkHttpUtil
import okhttp3.Call
import org.json.JSONObject
import java.io.IOException


/**
 *  @time 2025/5/14  9:07
 *  @desc 分类-小类
 */
class TypePopuWindow() : PopupWindow(), OnClickListener {

    private lateinit var mContext: Activity
    private lateinit var mMenuView: View
    private lateinit var rcType: RecyclerView

    private var currentId = "0"
    private lateinit var adapterType: TypeAdapter
    private var list = arrayListOf<SubMaterialModel>()
    private lateinit var callBackListener: LCInterface.LcCallBack

    fun init(context: Activity) {
        this.mContext = context
        findView()
        initPopu()
    }

    //初始化
    private fun initPopu() {
        this.contentView = mMenuView
        this.width = LayoutParams.MATCH_PARENT
        this.height = LayoutParams.MATCH_PARENT
        //设置SelectPicPopupWindow弹出窗体可点击
        this.isFocusable = false
        this.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
        this.isOutsideTouchable = false
        this.isTouchable = true
        this.isClippingEnabled = false ///覆盖状态栏，
        setTouchInterceptor { view, motionEvent -> false }
    }

    @SuppressLint("NewApi")
    private fun findView() {
        val inflater = mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        mMenuView = inflater.inflate(R.layout.view_type_popuwindow, null)
        rcType = mMenuView.findViewById(R.id.view_type_recycler)

        rcType.layoutManager = LinearLayoutManager(mContext)
        adapterType = TypeAdapter(mContext, list, object : LCInterface.LcCallBack {
            override fun callBack(vararg args: Any?) {
                val posiiton = args[0] as Int
                callBackListener.callBack(list[posiiton].id)
                dismiss()
            }
        })
        rcType.adapter = adapterType

    }


    override fun onClick(view: View?) {
        when (view?.id) {
            //地形
//            R.id.view_maplayer_terrain -> {
//                callBackListener.callBack("layout_terrain")
//            }
        }
    }

    fun showAtLocation(parent: View?, gravity: Int, x: Int, y: Int, id: String) {
//        setBackgroundAlpha(0.8f)
        if (currentId != id) {
            currentId = id
            list.clear()
            adapterType.notifyDataSetChanged()
            getSubMaterialList(id)
        }
        super.showAtLocation(parent, gravity, x, y)
    }

    /**
     *  @time 2024/7/8  16:39
     *  @author Im_jingwei
     *  @desc 事件回调接口
     */
    fun setPopuOnclickListener(listener: LCInterface.LcCallBack) {
        this.callBackListener = listener
    }

    /**
     *  @time 2024/5/7  11:29
     *  @desc 分类-小类
     *  @param url
     */
    fun getSubMaterialList(id: String) {
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_MAIN_SUBMATERIAL
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val params = JSONObject()
        params.put("pageSize", 0)
        params.put("pageNo", 1)
        params.put("categoryIds", id)
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequest(url, token, params.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val code = jsonObject.getInt("code")
                    val data = jsonObject.getJSONArray("data")
                    list.clear()
                    if (success) {
                        for (index in 0 until data.length()) {
                            val item = SubMaterialModel().apply { getModelInfo(data.getJSONObject(index)) }
                            list.add(item)
                        }
                        val item = SubMaterialModel().apply { subcategoryName = "清空" }
                        list.add(item)
                        mContext.runOnUiThread { adapterType.notifyDataSetChanged() }
                        LCLogger.d("LCLOG_SubMaterial", "获取成功！,数据：$jsonObject")
                    } else {
                        LCBaseUtil.showToast(mContext, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
                }
            }
        })
    }

    /**
     *  @time 2024/7/8  16:39
     *  @author Im_jingwei
     *  @desc 销毁
     */
    override fun dismiss() {
        //关闭软键盘
        setBackgroundAlpha(1.0f)
        super.dismiss()
    }

    //设置窗口颜色
    private fun setBackgroundAlpha(bgAlpha: Float) {
        val lp = (mContext as Activity).window.attributes
        (mContext as Activity).window.setFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND, WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        lp.alpha = bgAlpha //0.0-1.0
        (mContext as Activity).window.attributes = lp
    }

}